package net.csdn.business.auth.component;

import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.domain.ResponseResult;
import net.csdn.business.common.enums.ResultCodeEnum;
import net.csdn.business.auth.utils.SecurityMessageSourceUtil;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * @Desc: Authentication异常处理自定义返回信息
 * @ClassName: CustomAuthExceptionEntryPoint
 * @Author: yourleige@163.com
 * @Date: 2022/9/26 11:39
 */
@Slf4j
@Component
@AllArgsConstructor
public class CustomAuthExceptionEntryPoint implements AuthenticationEntryPoint {

	private final ObjectMapper objectMapper;

	@Override
	@SneakyThrows
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		ResponseResult<String> result = new ResponseResult<>();
		result.setMsg(authException.getMessage());
		result.setData(authException.getMessage());
		result.setCode(ResultCodeEnum.FAIL.getCode());
		if (authException instanceof CredentialsExpiredException
				/*|| authException instanceof InsufficientAuthenticationException*/) {
			String msg = SecurityMessageSourceUtil.getAccessor().getMessage(
					"AbstractUserDetailsAuthenticationProvider.credentialsExpired", authException.getMessage());
			result.setMsg(msg);
			result.setCode(HttpStatus.HTTP_UNAUTHORIZED);
		}
		if (authException instanceof UsernameNotFoundException) {
			String msg = SecurityMessageSourceUtil.getAccessor().getMessage(
					"AbstractUserDetailsAuthenticationProvider.noopBindAccount", authException.getMessage());
			result.setMsg(msg);
		}

		if (authException instanceof BadCredentialsException) {
			String msg = SecurityMessageSourceUtil.getAccessor().getMessage(
					"AbstractUserDetailsAuthenticationProvider.badClientCredentials", authException.getMessage());
			result.setMsg(msg);
		}
		response.setStatus(HttpStatus.HTTP_OK);
		PrintWriter printWriter = response.getWriter();
		printWriter.append(objectMapper.writeValueAsString(result));
	}

}
